package models

import Tables._
import scala.slick.driver.MySQLDriver.simple._
import util.Constants

object Article {
  def queryById(id: Int) = {
    SlickDB.database.withSession {
      implicit session =>
        val list = Tables.Article.filter(_.id === id).list
        list
    }
  }

  def queryByPages(page: Int) = {
    SlickDB.database.withSession {
      implicit session =>
        val query = Tables.Article.sortBy(_.time desc).drop((page - 1) * Constants.PageSize)
          .take(Constants.PageSize)
        query.list
    }
  }

  def queryByTagAndPages(tag: String, page: Int) = {
    SlickDB.database.withSession {
      implicit session =>
        val query = for {
          cid <- Tables.Category.filter(_.name === tag).map(_.id)
          aids <- Tables.ArticleCategory.filter(_.cId === cid).map(_.aId)
          article <- Tables.Article.filter(_.id === aids)
        } yield article
        ((query.length.run-1) /Constants.PageSize +1,
        query.sortBy(_.time desc).drop((page - 1) * Constants.PageSize).take(Constants.PageSize).list)
    }
  }

  def getTotalPage: Int = {
    SlickDB.database.withSession {
      implicit session =>
        (Tables.Article.length.run-1) / Constants.PageSize + 1
    }
  }
  
  def delete(id:Int) = {
    SlickDB.database.withSession {
      implicit session =>
      Tag.deleteArticleTags(id)
      Tables.Article.filter(_.id === id).delete
    } 
  }

  def update(article: ArticleRow, tags: List[String]) = {
    SlickDB.database.withSession {
      implicit session =>
        val aid = article.id
        val query = for { a <- Tables.Article if a.id === aid }
          yield (a.title, a.shortcontent, a.content)
        query.update((article.title, article.shortcontent, article.content))
        Tag.deleteArticleTags(aid);
        Tag.addTags(aid, tags)
    }
  }

  def save(article: ArticleRow, tags: List[String]) = {
    SlickDB.database.withSession {
      implicit session =>
        val aid =
          (Tables.Article returning Tables.Article.map(_.id)) += article
        Tag.addTags(aid, tags)
    }
  }
}